<?php

if (!function_exists('upload_file')) {
    /**
     * 上传文件
     *
     * @param  object $file 文件对象
     * @param  string $path 存放路径
     * @param  integer $size 文件大小限制，单位：KB（默认 2048）
     * @param  array $allowedExtensions 允许上传的文件类型（默认 ['png', 'jpg', 'jpeg', 'gif', 'bmp']）
     * @return array
     */
    function upload_file($file, $path, $size = 2048, $allowedExtensions = null)
    {
        if (!$file) {
            return ['status' => false, 'msg' => '未上传文件'];
        }

        if (!$file->isValid()) {
            return ['status' => false, 'msg' => $file->getErrorMessage()];
        }

        if (!$allowedExtensions) {
            $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif', 'bmp'];
        }

        $extension = strtolower($file->getClientOriginalExtension());

        if ($extension && in_array($extension, $allowedExtensions)) {
            $size *= 1024;
            $fileSize = $file->getClientSize();

            if ($fileSize <= $size) {
                $name = uniqid();
                $filename = $name . '.' . $extension;
                $destinationPath = 'Uploads/' . $path . date('Y-m-d') . '/';

                if ($file->move($destinationPath, $filename)) {
                    $filePath = $destinationPath . $filename;

                    return [
                        'status' => true,
                        'file_path' => $filePath,
                        'name' => $name . '-' . $extension,
                        'extension' => $extension,
                        'file_size' => $fileSize,
                        'filename' => $file->getClientOriginalName()
                    ];
                } else {
                    return ['status' => false, 'msg' => $file->getErrorMessage()];
                }

            } else {
                return ['status' => false, 'msg' => '文件大小限制为：' . get_file_sizes($size)];
            }

        } else {
            return ['status' => false, 'msg' => '支持的文件类型为：' . implode('、', $allowedExtensions)];
        }
    }
}

if (!function_exists('get_file_sizes')) {
    /**
     * 获取最匹配的文件单位
     *
     * @param  string $size 文件大小，单位：B
     * @return string
     */
    function get_file_sizes($size)
    {
        $basic = 1024;
        $units = [' B', ' KB', ' MB', ' GB', ' TB'];

        for ($i = 0; $size >= $basic && $i < 4; $i++) {
            $size /= $basic;
        }

        return round($size, 2) . $units[$i];
    }
}


if (!function_exists('str_rands')) {
    function str_rands($length, $integer = false)
    {
        if (!$integer) {
            return str_random($length);
        }

        $str = '0123456789';

        $number = (string) rand(1, 9);

        $length--;

        for ($i = 0; $i < $length; $i++) {
            $rand = rand(0, 9);
            $number .= $str{$rand};
        }

        return $number;
    }
}